package com.lagou.edu.factory;

import com.lagou.edu.service.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description
 * @author: liuhongfei
 * @create: 2021/11/27 21:10
 */
@Component("proxyFactory")
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

    // private ProxyFactory() {
    //
    // }
    //
    // private static ProxyFactory proxyFactory = new ProxyFactory();
    //
    // public static ProxyFactory getInstance() {
    //     return proxyFactory;
    // }

    /**
     * jdk动态代理
     *
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    transactionManager.begin();
                    result = method.invoke(obj, args);
                    transactionManager.commit();
                } catch (Exception e) {
                    transactionManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }
}
